# -*- coding:utf-8 -*-
# 通过调用kuboard，查看/更新镜像版本，调整容器数量

import json
from jsonpath import jsonpath
from flask import Flask, request, render_template
import requests
import datetime
import time
import logging
import mylog


app = Flask(__name__)
# 配置日志格式
time_tag = datetime.datetime.now().strftime("%Y-%m-%d")
log = mylog.Logger('all.log',level='debug')
logger = log.logger
requests.adapters.DEFAULT_RETRIES = 5 # 增加requests重连次数


# 更新镜像版本
@app.route("/updateimage/", methods=["GET", "POST"], strict_slashes=False)
def updateimage():
    logger.debug("In updateimage")
    # logger.debug('请求方式为------->', request.method)
    # 默认返回内容
    return_dict = {'return_code': '200', 'return_info': 'success', 'result': True}
    # 获取传入的参数 get
    # get_data = request.args.to_dict()
    # data_str =str(get_data.get('data'))
    # 获取传入的参数 post
    if request.method == "POST":
        data_str = request.form.to_dict()
        # print(data_str)

    qurey_data = data_str['imageName']
    env = data_str['env']
    # 判断入参是否为空
    if (qurey_data is None) or (env is None):
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = '必填请求参数不能为空'
        return_dict['result'] = 'False'
        return json.dumps(return_dict, ensure_ascii=False)
    # 不同的环境，地址，token信息不同
    # logger.debug(qurey_data)
    # sim：演示环境；uat：测试环境；zljuat：足力健测试环境；
    if env == 'sim':
        env_name = "演示环境"
        basurl = r"https://hkkuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/sim/deployments"
        token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IkRMS0NPRnlOVXFLWWxHM1FmUnlad2pnX2FxajBXVnpqX19iWWdZWk5tdEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZXYiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi10NXI4NCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNGIyNDA3OWYtYjk1YS00ZDk3LTgwODItMzNjYjk4NzIzY2UzIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRldjpoay1kZXZ1c2VyIn0.FOVsg0DMQvtn1yluVWz3g5V3YmoHD4ZtY3KRfJyo6A7lAw94st3Nyi8lfv7Y92c1rKGbCzAgcI6qCSQx0hMj4_zFcbsw5J3Lk9T7aAYF7nyOlA_t7HxdcBkrs6hTOucnFphaOWeWGTr7uutYgiw4xp3U-Q-lAO8n-gSxxxc1DkRqEf01yLHbEGGR4EsgS4TYiRJONu8Gy8SZUSomzEFed_djJLnZzuE5ewY3e7Z3LTzgWiLANemiIzTN-pvWoHtOonSGtqlQmsSbdASF-kHu5Zj65SK4U8_0SpvizC0HUuJNxaXeOzA8iv0GkpM2oswZCdMEqM6jcu7EoC3zCYcAJQ"
    if env == 'uat':
        env_name = "阿里云测试环境"
        basurl = r"https://hkkuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IkRMS0NPRnlOVXFLWWxHM1FmUnlad2pnX2FxajBXVnpqX19iWWdZWk5tdEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZXYiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi10NXI4NCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNGIyNDA3OWYtYjk1YS00ZDk3LTgwODItMzNjYjk4NzIzY2UzIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRldjpoay1kZXZ1c2VyIn0.FOVsg0DMQvtn1yluVWz3g5V3YmoHD4ZtY3KRfJyo6A7lAw94st3Nyi8lfv7Y92c1rKGbCzAgcI6qCSQx0hMj4_zFcbsw5J3Lk9T7aAYF7nyOlA_t7HxdcBkrs6hTOucnFphaOWeWGTr7uutYgiw4xp3U-Q-lAO8n-gSxxxc1DkRqEf01yLHbEGGR4EsgS4TYiRJONu8Gy8SZUSomzEFed_djJLnZzuE5ewY3e7Z3LTzgWiLANemiIzTN-pvWoHtOonSGtqlQmsSbdASF-kHu5Zj65SK4U8_0SpvizC0HUuJNxaXeOzA8iv0GkpM2oswZCdMEqM6jcu7EoC3zCYcAJQ"
    if env == 'zljuat':
        env_name = "足力健测试环境"
        basurl = r"https://kuboard.zljllcy.com/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjRlQjctZ2V2Z0ZjN0ZmQ3BMYlJoTWg2MWxWZ3ZxWFZjSnI5ODhLRTRkZEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1rOXA1ZyIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWUxZmRhZWUtMTM2NS00MWJjLTllM2YtNTA2MGNlMDhhN2IyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.cuT2uBo94PbI1gdcxZ6YJMS6f6aw9ZQxAzK18hl_e8M7btBDiAdTQcj1EjkPSQIQzl2BR_3od5onYacjzWAW6cxIncQc2bWyq-k1TIh4RSc9l9zwGVsJ6uPMO7Z0MZcWn1xqgVLtQp_uQg5YXAsaAaUvk6kHuTkPbEKsHcpHeTjguxwnWQNKWGMCxBaIyKuUV6s5AEQQu7-0igWbzoFvm650KCa14yOj1yXAuXXByxPBmZ__YQshWDRAAn6lzhoPhkrh5RmIFkAyIW6F09u7IbCwA4PNK1RtxXjY_tjokYm7gYlWmK1JbBh3LPjLRvVhbQC64mX__Cv1VT1NIeDmeg"
    if env == 'zljpro':
        env_name = "足力健正式环境"
        basurl = r"https://kuboard.zljllcy.com/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjRlQjctZ2V2Z0ZjN0ZmQ3BMYlJoTWg2MWxWZ3ZxWFZjSnI5ODhLRTRkZEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1rOXA1ZyIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWUxZmRhZWUtMTM2NS00MWJjLTllM2YtNTA2MGNlMDhhN2IyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.cuT2uBo94PbI1gdcxZ6YJMS6f6aw9ZQxAzK18hl_e8M7btBDiAdTQcj1EjkPSQIQzl2BR_3od5onYacjzWAW6cxIncQc2bWyq-k1TIh4RSc9l9zwGVsJ6uPMO7Z0MZcWn1xqgVLtQp_uQg5YXAsaAaUvk6kHuTkPbEKsHcpHeTjguxwnWQNKWGMCxBaIyKuUV6s5AEQQu7-0igWbzoFvm650KCa14yOj1yXAuXXByxPBmZ__YQshWDRAAn6lzhoPhkrh5RmIFkAyIW6F09u7IbCwA4PNK1RtxXjY_tjokYm7gYlWmK1JbBh3LPjLRvVhbQC64mX__Cv1VT1NIeDmeg"
    if env == 'psuat':
        env_name = "宝胜测试环境"
        basurl = r"http://pskuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        token = "eyJhbGciOiJSUzI1NiIsImtpZCI6Im1wMmNyVDNqMmg4ZDlLNjA3YTNNcGpwMkpWMTMzUTR1akFRbmlic1VkS0EifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1mbmRzNSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOWI1ZGMzZGMtOWJiYy00Y2I5LWE4MTAtNGI4NGZjYzJkYTdmIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.dOBRbjGUCDty9npLZEfJHG653zQouOimTWye0pc7onv3w0sEICPoTPYX2stYrNrhL_dQZzii6pIs8Erd66bL7F-3m-Y-0a9NjXqYlSQgXJVpvx4hAMxaTOeOohv4YpvYOQcdTPPU3dYAsAyhNQ_XUe8rDfmyp1qQNAiXEhg10C6j5Oq5XVP5z4tNqb8zhP2029T1a0X0c9Jl-jnO2c5x60RhwZn23e5ci2vHHIB4Z02dWVul89Wa0bsmf0TXAmmMgBrfs2l5Ts1E77fbXlva0nG8jh7q6z2Es1DKHMvSdF6ou5pTBjfRRQX8scuNRwOso43b5dPFUribTTTwEr4WIg"
    if env == 'jmwuat':
        env_name = "九牧王测试环境"
        basurl = r"https://kuboard.joeone.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        token = "eyJhbGciOiJSUzI1NiIsImtpZCI6Im5OaTR2a3p0YkoxQjhqdGdQSWlJaGhnblpXZzdXX0pEUk9RNDV3V0U1dUUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi03czRkNiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWM0MmM0NjMtNTM2MC00ZDBjLWI4NzEtYjFkZmY4NDUyNjFkIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.GS_4XTQajW0IAblazR1sV3LKyWK9afdbDOSX7A9UNk1r6w_KQ_IAnaziZVVNTPOhU-rnsaSR-xmcVvoqLlDHfh2rkwpDU5nsc68n8gWPQYpVy7kH5EYmxpTPPjx7xtHHhPfTin8ilibAb072tMMjmd3RPdQJutthqFDx2OQx1NAZDA2s1PYT4lKXW-dR9zspw8bKeBPoW-zidCsKXGeTsX6H55oxAc1WlGYm0v7qQatzIHzbo6hM2fIgP83LGh5l-RJv5Ik6KXtCEp921a5E9xG2Dpys-O0ONpnQAdEsBCSG1lOoHwam008bDvvpAoSMFJEE2JQzcKalVyiqRnqygw"
    if env == 'lspro':
        env_name = "联晟正式环境"
        basurl = r"https://kuboard.missonep.com/k8s-api/apis/apps/v1/namespaces/prod/deployments"
        token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IlRHcjNLbzFHMHBpLVRVWDVzdUdIV2UtQWlZUFcxSXRfcjVwVzhJamp6QkEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJwcm9kIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImhrLWRldnVzZXItdG9rZW4tYnFreDUiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiaGstZGV2dXNlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjFhOTI5ZDJkLWM2NmItNDI4NC05OWI1LWNjMTViYzgxMmU1NyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpwcm9kOmhrLWRldnVzZXIifQ.IP1Alw5lmXsIkpyS9Km5IZH8FK_7aYhSMVjixH6zx4G9huTGyIKjyj0Ep-ew-YHepL5CNrXh3QPFDHb2GLnNi18M6MK7chYMg4UTAy5NLawLn_dy8WXuT_H35NH_1UQvKraxIJGa9pn5FhzHALCVXGFaF3wrNhb1ehCIPPfLGqOzVUZXZ80s5SEi8zRhiaeR_WhF3tlZLWMP34pUiPtlVVnQwTiSoJvxNlNFUrxonRyD7vi3__m5k2C2DS3nVo3_zgo9QmcNt--AD_ac1Q4Jj-zLTSu5p_Z6s1KNletRpArSjEIAcg3Si67K3GHyqATdEwkngxuFQhcsagMLUZD56w"

    # 请求报头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
        'Authorization': "Bearer " + token,
        'Content-Type': 'application/json-patch+json'
    }
    response = requests.get(basurl, headers=headers, verify=False)
    logger.debug(response)
    # 提取镜像信息
    env_imags_info = {}
    cnt = len(jsonpath(response.json(), "$.items[*].metadata.name"))
    for i in range(cnt):
        image_xpath = "$.items[" + str(i) + "].spec.template.spec.containers[0].image"
        space_name = "$.items[" + str(i) + "].spec.template.spec.containers[0].name"
        tmp = jsonpath(response.json(), image_xpath)[0]
        # 镜像版本
        image_name_url, image_name = tmp.split(":")
        # 镜像仓库名称
        image_tag = image_name.split("-")[-1]
        image_space = jsonpath(response.json(), space_name)[0]
        # 形成镜像信息字典
        env_imags_info[image_tag] = {"space": image_space, "image": image_name, "image_url": image_name_url}
        # print(image_name_url)
        # print(image_space)
        # print(image_tag)
    # logger.debug(env_imags_info)

    # 更新镜像
    for image in qurey_data.split("\n"):
        image = image.strip()
        input_tag = image.split("-")[-1]
        # 相同镜像不更新
        if image.lower() == env_imags_info[input_tag]["image"]:
            logger.info("服务器已经是这个镜像版本：" + image)
        else:
            # 更新的空间命名（docker部署空间）
            updat_space = env_imags_info[input_tag]["space"]
            # 更新报文里面的镜像要包含对应的镜像路径
            updat_image = env_imags_info[input_tag]["image_url"] + ":" + image
            # 接口路径，具体到镜像
            update_url = basurl + "/" + updat_space
            updat_data = [{"op":"replace","path":"/spec/template/spec/containers/0/image","value": updat_image }]
            response = requests.patch(update_url, json=updat_data ,headers=headers)
            if response.status_code == 200:
                logger.info("更新成功")
                logger.info(env_imags_info[input_tag]["image"] + ' --> ' + image)
                logger.info(env_name + "镜像更新成功：" + env_imags_info[input_tag]["image"] + ' --> ' + image)
            else:
                logger.info("更新失败")
                return_dict['return_code'] = '5022'
                return_dict['return_info'] = '更新失败，失败镜像:' + image
                return_dict['result'] = 'False'

            # print(updat_data)
    # time.sleep(5)
    return json.dumps(return_dict, ensure_ascii=True)


# 根据返回页面，获取镜像信息（名称、路径）
def image_info_extract(response_str):
    # 提取镜像信息
    env_imags_info = {}
    cnt = len(jsonpath(response_str.json(), "$.items[*].metadata.name"))
    for i in range(cnt):
        replica = "$.items[" + str(i) + "].spec.replicas" # 副本数量
        replica_cnt = jsonpath(response_str.json(), replica)[0]
        # 副本数量为0，认为该副本已经停用
        if int(replica_cnt) > 0:
            image_xpath = "$.items[" + str(i) + "].spec.template.spec.containers[0].image"
            space_name = "$.items[" + str(i) + "].spec.template.spec.containers[0].name"
            tmp = jsonpath(response_str.json(), image_xpath)[0]
            # 镜像版本
            # 镜像中可能出现多个冒号，类似这种【hub.hengkangit.com:6337/hk_docker/guiderapp:202003150250-guiderapp】
            tmp_list = []
            tmp_list = tmp.split(":")
            if len(tmp_list) > 2:
                image_name_url = ":".join(tmp_list[0:-1])
            else:
                image_name_url = tmp_list[0]
            image_name = tmp_list[-1]
            # print(image_name)
            # 镜像仓库名称
            image_tag = image_name.split("-")[-1]
            # print(image_name)
            image_space = jsonpath(response_str.json(), space_name)[0]
            # 形成镜像信息字典
            # 当部署的环境中，有多个命名空间，可能存在有docker名称重复，但是运行着不同的版本的情况。要对镜像标签做检查，防止多个同名镜像标签覆盖
            if image_tag not in env_imags_info.keys():
                env_imags_info[image_tag] = {"space": image_space, "image": image_name, "image_url": image_name_url}
            else:
                tmp_tag = image_tag + "-1"
                env_imags_info[tmp_tag] = {"space": image_space, "image": image_name, "image_url": image_name_url}
                # env_imags_info['err'] = {"info": "存在同名但不同版本的镜像docker", image_tag}
    # logger.debug(env_imags_info)
    return env_imags_info

# 环境版本差异对比
@app.route("/imagediff_info", methods=["GET", "POST"], strict_slashes=False)
def image_diff_info():
    logger.debug("In imagediff_info")
    # 环境配置信息
    env_config = {"sim":{}, "uat":{}, "pro":{}, "zljuat":{}, "zljpro":{}, "psuat":{}, "jmwuat":{}, "lspro":{}}
    env_config["sim"]['env_name'] = "演示环境"
    env_config["sim"]['basurl']   = r"https://hkkuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/sim/deployments"
    env_config["sim"]['token']    = "eyJhbGciOiJSUzI1NiIsImtpZCI6IkRMS0NPRnlOVXFLWWxHM1FmUnlad2pnX2FxajBXVnpqX19iWWdZWk5tdEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZXYiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi10NXI4NCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNGIyNDA3OWYtYjk1YS00ZDk3LTgwODItMzNjYjk4NzIzY2UzIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRldjpoay1kZXZ1c2VyIn0.FOVsg0DMQvtn1yluVWz3g5V3YmoHD4ZtY3KRfJyo6A7lAw94st3Nyi8lfv7Y92c1rKGbCzAgcI6qCSQx0hMj4_zFcbsw5J3Lk9T7aAYF7nyOlA_t7HxdcBkrs6hTOucnFphaOWeWGTr7uutYgiw4xp3U-Q-lAO8n-gSxxxc1DkRqEf01yLHbEGGR4EsgS4TYiRJONu8Gy8SZUSomzEFed_djJLnZzuE5ewY3e7Z3LTzgWiLANemiIzTN-pvWoHtOonSGtqlQmsSbdASF-kHu5Zj65SK4U8_0SpvizC0HUuJNxaXeOzA8iv0GkpM2oswZCdMEqM6jcu7EoC3zCYcAJQ"
    env_config["uat"]['env_name'] = "阿里云测试环境"
    env_config["uat"]['basurl']   = r"https://hkkuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
    env_config["uat"]['token']    = "eyJhbGciOiJSUzI1NiIsImtpZCI6IkRMS0NPRnlOVXFLWWxHM1FmUnlad2pnX2FxajBXVnpqX19iWWdZWk5tdEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZXYiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi10NXI4NCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNGIyNDA3OWYtYjk1YS00ZDk3LTgwODItMzNjYjk4NzIzY2UzIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRldjpoay1kZXZ1c2VyIn0.FOVsg0DMQvtn1yluVWz3g5V3YmoHD4ZtY3KRfJyo6A7lAw94st3Nyi8lfv7Y92c1rKGbCzAgcI6qCSQx0hMj4_zFcbsw5J3Lk9T7aAYF7nyOlA_t7HxdcBkrs6hTOucnFphaOWeWGTr7uutYgiw4xp3U-Q-lAO8n-gSxxxc1DkRqEf01yLHbEGGR4EsgS4TYiRJONu8Gy8SZUSomzEFed_djJLnZzuE5ewY3e7Z3LTzgWiLANemiIzTN-pvWoHtOonSGtqlQmsSbdASF-kHu5Zj65SK4U8_0SpvizC0HUuJNxaXeOzA8iv0GkpM2oswZCdMEqM6jcu7EoC3zCYcAJQ"
    env_config["pro"]['env_name'] = "阿里云正式环境"
    env_config["pro"]['basurl']   = r"https://kuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/zj/deployments"
    env_config["pro"]['token']    = "eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImhrLWRldnVzZXItdG9rZW4tcWtwZmIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiaGstZGV2dXNlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjMwZDY4MTFlLTdhN2QtMTFlYy1iNTkyLTAwMTYzZTA2MzdhMiIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmhrLWRldnVzZXIifQ.EykQn4-fdmcgwoF3uGYVYsgLuqLE67hpTnk6OAGbJtECYW3tpJCmocPac8_HIVJqrXlbcyu-1Qgq_CS27dcg6v0lDDetTUTKLFMRUu6FD3VF4dmNx8doicwvWrb3_T1RdHN6OpzpTy-cTe_g-2-3Ub69HizZAqpUQeuHTypDV-mT72X-ydpo_PhwwBb814yic6bAjL5WkkNXaulEwobLw0FaUtn3n29OGrDZJaJkH450X2ccSwELb8QWK-1wZ3blzixEAvFVaYrHD6-OuC5FIjfQk_Nb1oCTwsDaGwMW5yICDwsuOZq0XII8LYdAtXQRqzZwUJmrAslKUdYyVHh75A"
    env_config["zljuat"]['env_name'] = "足力健测试环境"
    env_config["zljuat"]['basurl']   = r"https://kuboard.zljllcy.com/k8s-api/apis/apps/v1/namespaces/uat/deployments"
    env_config["zljuat"]['token']    = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjRlQjctZ2V2Z0ZjN0ZmQ3BMYlJoTWg2MWxWZ3ZxWFZjSnI5ODhLRTRkZEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1rOXA1ZyIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWUxZmRhZWUtMTM2NS00MWJjLTllM2YtNTA2MGNlMDhhN2IyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.cuT2uBo94PbI1gdcxZ6YJMS6f6aw9ZQxAzK18hl_e8M7btBDiAdTQcj1EjkPSQIQzl2BR_3od5onYacjzWAW6cxIncQc2bWyq-k1TIh4RSc9l9zwGVsJ6uPMO7Z0MZcWn1xqgVLtQp_uQg5YXAsaAaUvk6kHuTkPbEKsHcpHeTjguxwnWQNKWGMCxBaIyKuUV6s5AEQQu7-0igWbzoFvm650KCa14yOj1yXAuXXByxPBmZ__YQshWDRAAn6lzhoPhkrh5RmIFkAyIW6F09u7IbCwA4PNK1RtxXjY_tjokYm7gYlWmK1JbBh3LPjLRvVhbQC64mX__Cv1VT1NIeDmeg"
    env_config["zljpro"]['env_name'] = "足力健正式环境"
    env_config["zljpro"]['basurl']   = r"https://kuboard.zljllcy.com/k8s-api/apis/apps/v1/namespaces/prod/deployments"
    env_config["zljpro"]['token']    = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjRlQjctZ2V2Z0ZjN0ZmQ3BMYlJoTWg2MWxWZ3ZxWFZjSnI5ODhLRTRkZEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1rOXA1ZyIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWUxZmRhZWUtMTM2NS00MWJjLTllM2YtNTA2MGNlMDhhN2IyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.cuT2uBo94PbI1gdcxZ6YJMS6f6aw9ZQxAzK18hl_e8M7btBDiAdTQcj1EjkPSQIQzl2BR_3od5onYacjzWAW6cxIncQc2bWyq-k1TIh4RSc9l9zwGVsJ6uPMO7Z0MZcWn1xqgVLtQp_uQg5YXAsaAaUvk6kHuTkPbEKsHcpHeTjguxwnWQNKWGMCxBaIyKuUV6s5AEQQu7-0igWbzoFvm650KCa14yOj1yXAuXXByxPBmZ__YQshWDRAAn6lzhoPhkrh5RmIFkAyIW6F09u7IbCwA4PNK1RtxXjY_tjokYm7gYlWmK1JbBh3LPjLRvVhbQC64mX__Cv1VT1NIeDmeg"
    env_config["psuat"]['env_name'] = "宝胜测试环境"
    env_config["psuat"]['basurl']   = r"https://pskuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
    env_config["psuat"]['token']    = "eyJhbGciOiJSUzI1NiIsImtpZCI6Im1wMmNyVDNqMmg4ZDlLNjA3YTNNcGpwMkpWMTMzUTR1akFRbmlic1VkS0EifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1mbmRzNSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOWI1ZGMzZGMtOWJiYy00Y2I5LWE4MTAtNGI4NGZjYzJkYTdmIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.dOBRbjGUCDty9npLZEfJHG653zQouOimTWye0pc7onv3w0sEICPoTPYX2stYrNrhL_dQZzii6pIs8Erd66bL7F-3m-Y-0a9NjXqYlSQgXJVpvx4hAMxaTOeOohv4YpvYOQcdTPPU3dYAsAyhNQ_XUe8rDfmyp1qQNAiXEhg10C6j5Oq5XVP5z4tNqb8zhP2029T1a0X0c9Jl-jnO2c5x60RhwZn23e5ci2vHHIB4Z02dWVul89Wa0bsmf0TXAmmMgBrfs2l5Ts1E77fbXlva0nG8jh7q6z2Es1DKHMvSdF6ou5pTBjfRRQX8scuNRwOso43b5dPFUribTTTwEr4WIg"
    env_config["jmwuat"]['env_name'] = "九牧王测试环境"
    env_config["jmwuat"]['basurl']   = r"https://kuboard.joeone.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
    env_config["jmwuat"]['token']    = "eyJhbGciOiJSUzI1NiIsImtpZCI6Im5OaTR2a3p0YkoxQjhqdGdQSWlJaGhnblpXZzdXX0pEUk9RNDV3V0U1dUUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi03czRkNiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWM0MmM0NjMtNTM2MC00ZDBjLWI4NzEtYjFkZmY4NDUyNjFkIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.GS_4XTQajW0IAblazR1sV3LKyWK9afdbDOSX7A9UNk1r6w_KQ_IAnaziZVVNTPOhU-rnsaSR-xmcVvoqLlDHfh2rkwpDU5nsc68n8gWPQYpVy7kH5EYmxpTPPjx7xtHHhPfTin8ilibAb072tMMjmd3RPdQJutthqFDx2OQx1NAZDA2s1PYT4lKXW-dR9zspw8bKeBPoW-zidCsKXGeTsX6H55oxAc1WlGYm0v7qQatzIHzbo6hM2fIgP83LGh5l-RJv5Ik6KXtCEp921a5E9xG2Dpys-O0ONpnQAdEsBCSG1lOoHwam008bDvvpAoSMFJEE2JQzcKalVyiqRnqygw"
    env_config["lspro"]['env_name'] = "联晟正式环境"
    env_config["lspro"]['basurl']   = r"https://kuboard.missonep.com/k8s-api/apis/apps/v1/namespaces/prod/deployments"
    env_config["lspro"]['token']    = "eyJhbGciOiJSUzI1NiIsImtpZCI6IlRHcjNLbzFHMHBpLVRVWDVzdUdIV2UtQWlZUFcxSXRfcjVwVzhJamp6QkEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJwcm9kIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImhrLWRldnVzZXItdG9rZW4tYnFreDUiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiaGstZGV2dXNlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjFhOTI5ZDJkLWM2NmItNDI4NC05OWI1LWNjMTViYzgxMmU1NyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpwcm9kOmhrLWRldnVzZXIifQ.IP1Alw5lmXsIkpyS9Km5IZH8FK_7aYhSMVjixH6zx4G9huTGyIKjyj0Ep-ew-YHepL5CNrXh3QPFDHb2GLnNi18M6MK7chYMg4UTAy5NLawLn_dy8WXuT_H35NH_1UQvKraxIJGa9pn5FhzHALCVXGFaF3wrNhb1ehCIPPfLGqOzVUZXZ80s5SEi8zRhiaeR_WhF3tlZLWMP34pUiPtlVVnQwTiSoJvxNlNFUrxonRyD7vi3__m5k2C2DS3nVo3_zgo9QmcNt--AD_ac1Q4Jj-zLTSu5p_Z6s1KNletRpArSjEIAcg3Si67K3GHyqATdEwkngxuFQhcsagMLUZD56w"

    # logger.debug('请求方式为------->', request.method)
    # 默认返回内容
    return_dict = {'return_code': '200', 'return_info': 'success', 'result': True}
    # 获取传入的参数 get
    # get_data = request.args.to_dict()
    # data_str =str(get_data.get('data'))
    # 获取传入的参数 post
    if request.method == "POST":
        data = request.form.to_dict()

    env_s = data['env_s']
    env_t = data['env_t']
    cmptype = data['cmptype']
    # tmp_env = data['env']
    url_s = env_config[env_s]['basurl']
    token_s = env_config[env_s]['token']
    url_t = env_config[env_t]['basurl']
    token_t = env_config[env_t]['token']
    s = requests.session()
    s.keep_alive = False  # 关闭多余连接
    # 请求报头
    headers_s = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',
        'Authorization': "Bearer " + token_s,
        'Content-Type': 'application/json-patch+json'
    }
    headers_t = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',
        'Authorization': "Bearer " + token_t,
        'Content-Type': 'application/json-patch+json'
    }
    try:
        response_s = s.get(url_s, headers=headers_s, verify=False) # verify=False，解决SSL 根证书验错误
        response_t = s.get(url_t, headers=headers_t, verify=False) # verify=False，解决SSL 根证书验错误
        # print(response_s.text)
    except:
        logger.info("链接K8S失败")
        return_dict['return_info'] = "链接K8S失败"
        return json.dumps(return_dict, ensure_ascii=True)
    logger.debug(response_t.text)
    image_s = image_info_extract(response_s)
    image_t = image_info_extract(response_t)
    tmp_s = []
    tmp_t = []
    for k in image_s: tmp_s.append(image_s[k]['image'])
    for k in image_t: tmp_t.append(image_t[k]['image'])
    # print(tmp_s)
    # print(tmp_t)
    # 提取新的镜像
    # 遍历最长的字典
    for k in list(image_s.keys() if len(image_s.keys()) > len(image_t.keys()) else image_t.keys()):
        try:
            if image_s[k]['image'] == image_t[k]['image']:
                image_s.pop(k)
                image_t.pop(k)
            else:
                # 只保留新的镜像
                image_s.pop(k) if image_s[k]['image'] < image_t[k]['image'] else image_t.pop(k)
        except KeyError:
            if k in image_s:
                msg_str = str(env_t) + "环境" + "没有" + str(k) + "镜像"
            else:
                msg_str = str(env_s) + "环境" + "没有" + str(k) + "镜像"
            print("---->", cmptype)
            if int(cmptype) == 1:
                # 只保留非独有镜像
                if k in image_s:
                    image_s.pop(k)
                    print("fack:", k)
                else:
                    image_t.pop(k)
                    print("fack:", k)
            logger.info(msg_str)
    image_dict = {}
    tmp_s = ""
    tmp_t = ""
    env_str_s = env_config[env_s]['env_name']
    env_str_t = env_config[env_t]['env_name']
    for k in image_s.values(): tmp_s += k['image'] + ','
    for k in image_t.values(): tmp_t += k['image'] + ','
    image_dict[env_str_s] = tmp_s[0:-1]
    image_dict[env_str_t] = tmp_t[0:-1]
    return_dict['return_info'] = image_dict
    print(return_dict)
    return json.dumps(return_dict, ensure_ascii=True)


# 首页
@app.route("/", methods=["GET"])
def index():
    return render_template('index.html')

# 环境版本
@app.route("/imagediff", methods=["GET"])
def imagediff():
    return render_template('difImage.html')


if __name__ == "__main__":
    # con = open_db()
    app.run(host = "0.0.0.0",port=5002,debug=True)
